import React, { useEffect, useState } from 'react'
import Navbar from '../../../compounts/navber/Navbar'
import request from '../../../api/request'
import { Avatar, InfiniteScroll, Toast, Selector } from 'antd-mobile' // 移除Segmented
import { useNavigate, useSearchParams } from 'react-router-dom'
import style from './keshi.module.css'

function Index() {
    const nav = useNavigate()
    const [sp] = useSearchParams()

    // 筛选和排序状态
    const [condition, setCondition] = useState(1); // 1=综合, 2=好评, 3=咨询数, 4=价格
    const [sortBy, setSortBy] = useState(0);

    // 查询医生列表
    // 1. 修改getdoctorlist函数中的sortBy参数传递逻辑
    const getdoctorlist = (page) => {
        // 获取需要查看的条件，是综合还是好评等
        const numericCondition = isNaN(Number(condition)) ? 1 : Number(condition);

        // 发送请求
        return request.get('/user/inquiry/v1/findDoctorList', {
            params: {
                deptId: sp.get('id'),
                condition: numericCondition,
                page: page ? Number(page) : 1,
                count: 10,
            }
        }).then((res) => {
            console.log('请求参数:', res.config.params);
            return res.data.result;
        })
    };

    const togglePriceSort = () => {
        setSortBy((prev) => (prev === 0 ? 1 : 0));
    };

    // 3. 修改筛选条件切换时的排序状态重置逻辑
    <Selector
        options={[
            { label: '综合', value: '1' },
            { label: '好评', value: '2' },
            { label: '咨询数', value: '3' },
            { label: '价格', value: '4' },
        ]}
        defaultValue={['1']}
        onChange={(selectedValues) => {
            const selectedValue = selectedValues[0];
            const newCondition = Number(selectedValue);
            if (!isNaN(newCondition)) {
                setCondition(newCondition);
                // 切换筛选条件时重置排序状态
                setSortBy(0);
                console.log('切换筛选条件为:', newCondition);
            }
        }}
    />

    // 4. 确保价格排序按钮文本与sortBy值对应
    {
        condition === 4 && (
            <button
                className={`${style.sortButton} ${sortBy === 1 ? style.active : ''}`}
                onClick={togglePriceSort}
            >
                {sortBy === 1 ? '价格从高到低' : '价格从低到高'}
            </button>
        )
    }


    // 无限滚动相关状态和函数
    const [data, setData] = useState([])
    const [page, setPage] = useState(0)
    const [loadingMore, setLoadingMore] = useState(false)
    const [hasMore, setHasMore] = useState(true)

    const resetAndLoadData = async () => {
        setData([]);
        setPage(0);
        setHasMore(true);
        try {
            const firstPageData = await getdoctorlist(1);
            if (firstPageData) {
                setData(firstPageData);
            }
        } catch (error) {
            Toast.show('加载失败，请重试');
            console.error('加载医生数据失败:', error);
        }
    };

    async function loadMore() {
        if (loadingMore) return;
        setLoadingMore(true);
        try {
            const newPage = page + 1;
            const newData = await getdoctorlist(newPage);
            if (newData && newData.length > 0) {
                setData(val => [...val, ...newData]);
                setPage(newPage);
                if (newData.length < 10) {
                    setHasMore(false);
                }
            } else {
                setHasMore(false);
            }
        } catch (error) {
            Toast.show('加载失败，请重试');
            console.error('加载更多医生数据失败:', error);
        } finally {
            setLoadingMore(false);
        }
    }

    // 监听筛选条件变化
    useEffect(() => {
        resetAndLoadData();
    }, [condition, sortBy]);


    // 点击去往医生详情页
    const DoctorClick = (id) => {
        nav(`/doctorDetail?id=${id}`)
    }

    return (
        <div className={style.box}>
            <Navbar title={sp.get('name')}></Navbar>
            {/* 筛选排序栏 */}
            <div className={style.filterBar}>
                <div className={style.segmentedContainer}>
                    <Selector
                        columns={4}
                        options={[
                            { label: '综合', value: '1' },
                            { label: '好评', value: '2' },
                            { label: '咨询', value: '3' },
                            { label: '价格', value: '4' },
                        ]}
                        defaultValue={['1']}
                        onChange={(selectedValues) => {
                            // 从选中的值数组中获取第一个值并转为数字
                            const selectedValue = selectedValues[0];
                            const newCondition = Number(selectedValue);

                            // 确保newCondition是有效数字
                            if (!isNaN(newCondition)) {
                                setCondition(newCondition);
                                // 切换筛选条件时重置排序状态
                                setSortBy(0);
                                console.log('切换筛选条件为:', newCondition);
                            } else {
                                console.error('无效的筛选条件值:', selectedValue);
                            }
                        }}
                    />
                </div>

                {/* 价格排序按钮（仅当选中价格条件时显示） */}

                <div
                    className={`${style.sortButton} ${sortBy === 1 ? style.active : ''}`}
                    onClick={togglePriceSort}
                >
                    {sortBy === 1 ? '升序' : '降序'}
                </div>

            </div>
            <div className={style.doctorbox}>
                {data.length > 0 ? (
                    data.map((item, index) => (
                        <div className={style.doctorlist} key={index} onClick={() => DoctorClick(item.doctorId)}>
                            <div><Avatar src={item.imagePic} style={{ '--size': '64px', '--border-radius': '50px' }} /></div>
                            <div className={style.jiasao}>
                                <h5 className={style.name}>{item.doctorName} {item.jobTitle}</h5>
                                <p className={style.yiyuan}>{item.inauguralHospital}</p>
                                <div className={style.shanchang}>
                                    擅长：{item.specialty || '擅长治疗颅内动脉肿瘤、脑和脊髓血管畸形、颈动脉海绵溃缩、硬化等'}
                                </div>
                            </div>
                        </div>
                    ))
                ) : (
                    <div className={style.noData}>暂无医生数据</div>
                )}
                {/* 无限滚动 */}
                <InfiniteScroll loadMore={loadMore} hasMore={hasMore}>
                    {loadingMore && (
                        <div className={style.loadingMore}>
                            加载中...
                        </div>
                    )}
                    {!hasMore && !loadingMore && (
                        <div className={style.noMoreData}>
                            没有更多数据了
                        </div>
                    )}
                </InfiniteScroll>
            </div>
        </div>
    )
}

export default Index
